import { fetchApi } from './index';


/**
 * 初始化 session
 * @returns {Promise<string>} - 生成的 session ID
 */

export const SESSION_KEYS = {
    _SESSION_ID: 'sessionId'
};


export const initSession = async () => {
    const sessionId = sessionStorage.getItem('sessionId');
    if (sessionId) {
        return sessionId;
    }
    const response = await fetchApi('/api/init/session');
    const newSessionId= response[Object.keys(response)[0]];
    console.log("init sessionId", newSessionId);
    sessionStorage.setItem(SESSION_KEYS._SESSION_ID, newSessionId)
    return newSessionId;
};

// 获取 session id
export const getSessionId = () => {
    return sessionStorage.getItem(SESSION_KEYS._SESSION_ID);
};

// 清除 session id
 export const clearSession = () => {
    sessionStorage.removeItem(SESSION_KEYS._SESSION_ID);
};

// 在请求头中添加 session id
 export const addSessionToRequest = (originalFetch: typeof fetch) => {
    return async (input: RequestInfo | URL, init: RequestInit = {}) => {
        const sessionId = getSessionId();
        if (sessionId) {
            init.headers = init.headers || {};
            (init.headers as Record<string, string>)['X-Session-ID'] = sessionId;
        }
        return originalFetch(input, init);
    };
};